<template>
	<div class="upload-box">
		<el-upload
			drag
			ref="upload"
			:disabled="disabled"
			:on-exceed="exceedFn"
			:limit="1"
			:before-upload="beforeUploadHandle"
			:http-request="uploadFn"
			:show-file-list="false"
		>
			<img v-if="modelValue" class="upload-show" :src="modelValue" alt="图片" />
			<div class="upload-img" v-else>
				<img src="@/assets/img/canvas/noImage.png" />
				<el-text class="p-y-10 f-s-12"> 图片需小于 {{ fileSize }}M ，格式为 {{ fileType.join('/') }}</el-text>
			</div>
		</el-upload>
	</div>
</template>

<script setup name="MyImgUploadOne">
import { formContextKey as elFormKey, genFileId } from 'element-plus';
import { FILE_PREFIX } from '@/config';

/**
 * 请求接口
 */
import { rdfileDataUpload } from '@a/public';

const emits = defineEmits(['update:modelValue', 'change']),
	elForm = inject(elFormKey, {}),
	fileType = ['png', 'jpg', 'jpeg', 'gif'],
	/***
	 * props
	 * @property {Array} modelValue v-model绑定的值，
	 * @property {Number} fileSize 上传文件大小的限制（默认为5M）
	 */
	props = defineProps({
		modelValue: String,
		fileSize: {
			type: Number,
			default: 5
		},
		disabled: Boolean
	});

// 是否禁用上传功能
const disabled = computed(() => props.disabled || elForm?.disabled);

// 文件超出个数限制时的钩子
const upload = shallowRef(null);
function exceedFn(files) {
	unref(upload).clearFiles();
	const file = files[0];
	file.uid = genFileId();
	unref(upload).handleStart(file);
	unref(upload).submit();
}

// 上传前校检格式和大小
function beforeUploadHandle(file) {
	// 校检文件类型
	let fileExtension = '';
	if (file.name.lastIndexOf('.') > -1) {
		fileExtension = file.name.slice(file.name.lastIndexOf('.') + 1);
	}
	const isTypeOk = fileType.some((type) => {
		if (file.type.indexOf(type) > -1) return true;
		if (fileExtension && fileExtension.indexOf(type) > -1) return true;
		return false;
	});
	if (!isTypeOk) {
		msgError(`文件格式不正确, 请上传${fileType.join('/')}格式文件!`);
		return false;
	}
	// 校检文件大小
	if (props.fileSize) {
		const isLt = file.size / 1024 / 1024 < props.fileSize;
		if (!isLt) {
			msgError(`上传文件大小不能超过 ${props.fileSize} MB!`);
			return false;
		}
	}
	return true;
}

// 自定义上传操作
const uploadFn = (options) => {
	const { file } = options;
	if (file) {
		const formdata = new FormData();
		formdata.append('file', file);
		rdfileDataUpload(formdata).then((res) => {
			const downloadUrl = FILE_PREFIX ? `${FILE_PREFIX}${res.data.storageUrl}` : res.data.downloadUrl;
			emits('update:modelValue', downloadUrl);
			emits('change', downloadUrl);
		});
	} else {
		msgError('添加图片失败，请稍后重试！');
	}
};
</script>

<style lang="scss" scoped>
$uploadHeight: 150px;

.upload-box {
	cursor: pointer;

	:deep() {
		.el-upload-dragger {
			width: 100%;
			padding: 5px;
			background-color: rgb(0 0 0 / 0%);
		}
	}

	.upload-show {
		width: 100%;
		height: $uploadHeight;
		object-fit: contain;
		border-radius: 5px;
	}

	.upload-img {
		display: flex;
		flex-direction: column;
		align-items: center;

		img {
			width: 70%;
		}
	}
}
</style>
